/*
 * FileUtils.h
 *
 *  Created on: Jun 18, 2013
 *      Author: alexandru
 */


#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "FileResult.h"


#ifndef FILEUTILS_H_
#define FILEUTILS_H_

struct SimpleObject{
	string propertyName;
	string propertyValue;
};

FileResult stn_readFile(char *path);
vector<SimpleObject> stn_getVarsFromFile(char *path);
FileResult stn_getStdOutFromCommand(string command);


class ObjectsFromFile{
public:
	ObjectsFromFile(char *path){
		objectList=stn_getVarsFromFile(path);
	}

	~ObjectsFromFile(){

	}


	string getPropertyByName(string param_propertyName){
		for(unsigned int i=0; i<objectList.size(); i++){
			if(objectList.at(i).propertyName==param_propertyName){
				return objectList.at(i).propertyValue;
			}
		}
		return "undefined property name";
	}

private:
	vector<SimpleObject> objectList;
};


FileResult stn_getStdOutFromCommand(string command){
	FileResult result;

	FILE * stream;
	const int max_buffer = 256;
	char buffer[max_buffer];
	command.append(" 2>&1");
	stream = popen(command.c_str(), "r");
	if (stream) {
		while (!feof(stream)){
			if (fgets(buffer, max_buffer, stream) != NULL) {
				result.addLine(string(buffer));
			}
		}
		pclose(stream);
	}

	return result;
}


vector<SimpleObject> stn_getVarsFromFile(char *path){
	FileResult result=stn_readFile(path);
	vector<string> lines=result.getLines();
	vector<SimpleObject> objects;

	for(unsigned int i=0; i< lines.size(); i++){
		string propValue;
		string propName;
		string currentline=lines.at(i);
		string::size_type pos=currentline.find("=");
		if(pos != std::string::npos) {
				propName=currentline.substr(0, pos);
				propValue=currentline.substr(pos+1);
				SimpleObject obiect;
				obiect.propertyName=propName;
				obiect.propertyValue=propValue;
				objects.push_back(obiect);
				//cout << propName << " ... " << propValue << endl;
			}
	}

	return objects;
}



FileResult stn_readFile(char *path){
	FileResult composedData;
	ifstream fin;                          // Declaring an input stream object
	string outPut;
	string result="";
	fin.open(path);
	if(fin.is_open())                      // If it opened successfully
		{

			while (getline(fin, outPut)) {
				composedData.addLine(outPut);
			}
			fin.close();
			return composedData;
		}
	return composedData;
}










#endif /* FILEUTILS_H_ */
